package com.qian.fmall.user.service;

import com.mysql.cj.util.StringUtils;
import com.qian.fmall.commons.ResultSet;
import com.qian.fmall.commons.utils.Constant;
import com.qian.fmall.commons.utils.MD5Utils;
import com.qian.fmall.mapper.UserAddrMapper;
import com.qian.fmall.mapper.UserMapper;
import com.qian.fmall.pojo.User;
import com.qian.fmall.user.UserService;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.DefaultJwtBuilder;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

@Service
@DubboService
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserAddrMapper userAddrMapper;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public ResultSet userLogin(String name, String pwd) {
        if(!StringUtils.isNullOrEmpty(name))
        {
            User user = userMapper.selectUserByName(name);
            System.err.println("user-----------------------------"+user);
            if(user!=null)
            {
                if(!StringUtils.isNullOrEmpty(pwd))
                {
                    if(MD5Utils.md5(pwd).equals(user.getPassword()))
                    {
                        String v=UUID.randomUUID().toString().replace("-","");
                        ValueOperations vo = redisTemplate.opsForValue();
                        vo.set(Constant.KEY_HEAD+user.getUsername(),v);

                        HashMap map = new HashMap();
                        map.put("username",user.getUsername());
                        DefaultJwtBuilder defaultJwtBuilder = new DefaultJwtBuilder();
                        String token = defaultJwtBuilder.setIssuedAt(new Date())
                                .setSubject(name)
                                .setClaims(map)
                                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60))
                                .signWith(SignatureAlgorithm.HS256, MD5Utils.md5(MD5Utils.md5(v)))
                                .compact();
                        return ResultSet.ok(token,user);
                    }
                    else {
                        return ResultSet.error("密码不正确");
                    }
                }
                return ResultSet.error("密码为空");
            }
            return ResultSet.error("用户名不存在");
        }
        return ResultSet.error("输入的用户名为空");
    }

    @Override
    public ResultSet getAddr(String userId) {
        return ResultSet.ok("success",userAddrMapper.selectUserAddrByUserId(userId));
    }


}
